package com.bdqn.t362.pay.servlet;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.bdqn.t362.pay.AlipayApiConfig;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lqm
 * @ClassName ${NAME}
 * @description: TODO
 */
@WebServlet( "/AliPayServlet")
public class AliPayServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //创建订单





        AlipayClient alipayClient = new DefaultAlipayClient(AlipayApiConfig.URL,
                AlipayApiConfig.APP_ID, AlipayApiConfig.PRIVATE_KEY, AlipayApiConfig.FORMAT,
                AlipayApiConfig.CHARSET, AlipayApiConfig.ALIPAY_PUBLIC_KEY,
                AlipayApiConfig.SIGN_TYPE);
        AlipayTradePagePayRequest req = new AlipayTradePagePayRequest();
//异步接收地址，仅支持http/https，公网可访问
//req.setNotifyUrl("");
//同步跳转地址，仅支持http/https
        req.setReturnUrl("http://localhost:8080/projectManager_war_exploded/PayCallBackServlet");
/******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", "SO20210817010101008_"+11);
//支付金额，最小值0.01元
        bizContent.put("total_amount", 0.01);
//订单标题，不可使用特殊符号
        bizContent.put("subject", "测试商品");
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        req.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse resp = null;
        try {
            resp = alipayClient.pageExecute(req);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (resp.isSuccess()) {
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            response.setContentType("text/html;charset=" + AlipayApiConfig.CHARSET);
            System.out.println(resp.getBody());
            out.print(resp.getBody());
            out.flush();
            out.close();
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

    }
}
